<?php

namespace app\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class RightValidate
{
    public function handle(Request $request, Closure $next) {
        // dd($request->route()->action['controller']);
        // $res = substr(strrchr($request->route()->action['controller'], '\\'), 1);
        $res = substr(strrchr($request->route()->getActionName(), '\\'), 1);
        list($controller, $action) = explode('@', $res);
        $menu = DB::table('admin_menus')
            ->where('controller', $controller)
            ->where('action', $action)
            ->first();
        if (!$menu) {
            $this->errMsg('该功能不存在');
        }
        if ($menu->status) {
            $this->errMsg('该功能被禁用，联系管理员');
        }
        $admin = Auth::user();
        $group = DB::table('admin_group')->where('id', $admin->gid)->first();
        if (!$group) {
            $this->errMsg('角色不存在，联系管理员');
        }
        $admin->group_title = $group->title;
        $admin->rights = json_decode($group->rights);
        if (!in_array($menu->id, $admin->rights)) {
            $this->errMsg('无权访问');
        }
        $request->admin = $admin;
        return $next($request);
    }

    private function errMsg($msg) {
        if (request()->ajax()) {
            exit(json_encode(['code' => 1, 'msg' => $msg]));
        }
        exit("<p style='text-align:center'>$msg</p>");
    }
}
